<template>
  <div class="filter">
    <t-drawer
      size="695px"
      :visible.sync="visible"
      :closeBtn="false"
      @confirm="handleConfirm"
      :close-on-overlay-click="false"
    >
      <template #header>
        <div class="drawer-head" @click="close">
          <p class="chevron-left">
            <icon-font name="chevron-left" size="18px" />
          </p>
          <h3>{{header}}</h3>
        </div>
      </template>
      <t-form :data="formData" :rules="rules" ref="form" label-align="top" @submit="onSubmit">
        <t-form-item label="图标" name="thumbnail">
          <upload-img module="product" :value="formData.icon ? [{url: formData.icon}] : []" @success="handleSuccess($event, 'icon')" @remove="handleRemove($event, 'icon')"></upload-img>
        </t-form-item>
        <t-form-item label="上级分类" name="pid">
          <t-cascader v-model="formData.pid" :options="classifyOptions" placeholder="请选择产品分类"></t-cascader>
        </t-form-item>
        <t-form-item label="分类名称" name="title">
          <t-input v-model="formData.title" placeholder="请输入分类名称"></t-input>
        </t-form-item>
        <t-form-item label="分类编号" name="sn">
          <t-input v-model="formData.sn" placeholder="请输入分类编号"></t-input>
        </t-form-item>
        <t-form-item label="分类描述" name="desc">
          <t-textarea v-model="formData.desc" placeholder="请输入分类描述"></t-textarea>
        </t-form-item>
        <t-form-item label="排序" name="sort">
          <t-input-number v-model="formData.sort" style="width: 220px;" placeholder="输入排序"></t-input-number>
        </t-form-item>
        <t-form-item label="状态" name="status">
          <t-radio-group v-model="formData.status" :options="statusOptions"></t-radio-group>
        </t-form-item>
      </t-form>
    </t-drawer>
  </div>
</template>

<script>
import { IconFont } from "tdesign-icons-vue";
import UploadImg from "@/components/upload-img/index.vue";
import {classifyCreateApi, classifyDetailApi, classifyEditApi, classifyListApi} from "@/api/classify";

export default {
  name: 'ClassifyAdd',
  components: {IconFont, UploadImg},
  data() {
    return {
      visible: false,
      header: '新增分类',
      formData: {
        pid: 0,  // 父级
        belong_module: 'product_classify', // 模块类型（如产品分类 product_classify，品牌 product_brand，发货说明 product_deliver，分类 product_safeguard...）
        belong_id: '', // 模块id
        title: '', // 标题
        name: '', // 名称
        sn: '', // 编号
        desc: '', // 描述
        icon: '', // 图标
        sort: 999, // 排序
        config_data: '', // 配置数据
        status: '1', // 状态
      },
      rules: {
        pid: [{required: true, message: '请选择上级分类', trigger: 'change'},],
        //icon: [{required: true, message: '请上传图标', trigger: 'change'},],
        //belong_id: [{required: true, message: '请选择模块', trigger: 'change'},],
        title: [{required: true, message: '请输入分类名称', trigger: 'blur'},],
        //sn: [{required: true, message: '请输入分类编号', trigger: 'blur'},],
        //desc: [{required: true, message: '请输入分类描述', trigger: 'blur'},],
        sort: [{required: true, message: '请输入排序', trigger: 'blur'},],
        status: [{required: true, message: '请选择状态', trigger: 'change'},],
      },
      classifyOptions: [
        { label: '顶级分类', value: 0 },
      ],
      statusOptions: [
        {label: '启用', value: 1},
        {label: '禁用', value: 0},
        {label: '作废', value: -1},
      ],
    }
  },
  methods: {
    handleSuccess(files, key) {
      this.formData[key] = files.response.url
    },
    handleRemove(files, key) {
      this.formData[key] = ''
    },
    // 确认
    handleConfirm() {
      this.$refs.form.submit()
    },
    onSubmit({ validateResult, firstError }) {
      if (validateResult === true) {
        this.handleSubmit()
      } else {
        this.$message.warning(firstError);
      }
    },
    handleSubmit() {
      const request = this.type === 'edit' ? classifyEditApi : classifyCreateApi
      request(this.formData).then(res=> {
        this.$message.success(this.type === 'edit' ? '编辑成功' : '新增成功')
        this.close()
        this.$emit('refresh')
      }).catch(err=> {
        console.log(err)
      })
    },
    getDetail() {
      classifyDetailApi({id: this.editId}).then(res=> {
        const { data } = res
        this.formData = {
          pid: data.pid,  // 父级
          belong_module: data.belong_module, // 模块类型（如产品分类 product_classify，分类 product_brand，发货说明 product_deliver，保障说明 product_safeguard...）
          belong_id: data.belong_id, // 模块id
          title: data.title, // 标题
          name: data.name, // 名称
          sn: data.sn, // 编号
          desc: data.desc, // 描述
          icon: data.icon, // 图标
          sort: data.sort, // 排序
          config_data: data.config_data, // 配置数据
          status: data.status, // 状态
        }
        if (this.type === 'edit') {
          this.formData.id = data.id
          this.header = '编辑分类'
        }
      }).catch(err=> {
        console.log('err', err)
      })
    },
    // 获取列表
    getList() {
      const params = {
        page: 1,  // 当前页
        limit: 99999,  // 每页条数
        belong_module: 'product_classify', // 模块类型（如产品分类 product_classify，说明 product_brand，发货说明 product_deliver，保障说明 product_safeguard ...）
      }
      classifyListApi(params).then(res=> {
        const lists = res.data.map(item=> ({ label: item.title, value: item.id, id: item.id, pid: item.pid }))
        const hierarchy = this.buildHierarchyRecursive(lists)
        hierarchy.unshift({label: '顶级分类', value: 0, id: 0, pid: 0})
        this.classifyOptions = hierarchy
      }).catch(err=> {
        console.log('err', err)
      })
    },
    buildHierarchyRecursive(data, pid = 0) {
      return data
        .filter(item => item.pid === pid)
        .map(item => ({
          ...item,
          //children: this.buildHierarchyRecursive(data, item.id)
        }));
    },
    open(type, data={}) {
      this.editId = data.id
      this.type = type
      this.header = '新增分类'
      if (this.type === 'add') {
        this.formData = {
          pid: 0,  // 父级
          belong_module: 'product_classify', // 模块类型（如产品分类 product_classify，分类 product_brand，发货说明 product_deliver，保障说明 product_safeguard...）
          belong_id: '', // 模块id
          title: '', // 标题
          name: '', // 名称
          sn: '', // 编号
          desc: '', // 描述
          icon: '', // 图标
          sort: 999, // 排序
          config_data: '', // 配置数据
          status: 1, // 状态
        }
      } else if (this.type === 'edit' || this.type === 'copy') {
        this.getDetail();
      }
      this.getList();
      this.visible = true
    },
    close() {
      this.visible = false
    }
  }
}
</script>

<style lang="less" scoped>

</style>
